<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-08-15 16:45:26
 * @LastEditors: 李天惊 uf_lee@163.com
 * @LastEditTime: 2022-12-21 17:10:12
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Pasture\components\See.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
-->
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElButton } from 'element-plus'

import { ContentWrap } from '@/components/ContentWrap'
import { Descriptions } from '@/components/Descriptions'
import { Table } from '@/components/Table'

// 获取字典

import { useCache } from '@/hooks/web/useCache'
import { zcInventoryDetailedListApi } from '@/api/cy/Pan'
import { useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useTable } from '@/hooks/web/useTableTest'

// import FileSaver from 'file-saver'
// import * as XLSX from 'xlsx'
const { wsCache } = useCache()

import { Folder } from '@element-plus/icons-vue'
import { dbInventorySeeexportApi } from '@/api/forms'
/****************************** 变量 start ******************************/
const dict: any = wsCache.get('dict')
// const data = ref<any>({})
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const d_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  {
    field: 'enclosure_name',
    label: '栏位',
    width: 150
  },
  {
    field: 'asset_code',
    label: '注射编码',
    width: 200
  },
  {
    field: 'asset_code_2',
    label: '项圈编码',
    width: 200
  },
  {
    field: 'earcon_code',
    label: '耳标号',
    width: 200
  },
  {
    field: 'breed',
    label: '畜别',
    width: 100,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    }
  },
  {
    field: 'purpose',
    label: '用途',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('purpose', cellValue)
    }
  },
  {
    field: 'sex',
    label: '性别',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('animal_sex', cellValue)
    }
  },
  {
    field: 'should_number',
    label: '应盘数',
    width: 100
  },
  {
    field: 'actual_number',
    label: '实盘数',
    width: 100
  },
  {
    field: 'actual_number',
    label: '差异',
    width: 100
  },
  {
    field: 'create_time',
    label: '创建日期',
    width: 180
  }
  // {
  //   field: 'state',
  //   label: '状态',
  //   width: 150
  // },
  // {
  //   field: 'note',
  //   label: '备注',
  //   width: 150
  // },
  // {
  //   field: 'medical_user_name',
  //   label: '兽医名称',
  //   width: 150
  // },
  // {
  //   field: 'creation_time',
  //   label: '创建时间',
  //   width: 180
  // },
  // {
  //   field: 'action',
  //   width: 60,
  //   fixed: 'right',
  //   label: '操作'
  // }
])
/****************************** 变量 end ******************************/
const { allSchemas } = useCrudSchemas(d_columns)

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcInventoryDetailedListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList } = methods

/****************************** 组件参数 start ******************************/
// 获取参数
const props = defineProps({
  currentRow: {
    type: Object,
    default: () => null
  },
  detailSchema: {
    type: Array,
    default: () => []
  },
  id: {
    type: String,
    default: null
  }
})
/****************************** 组件参数 end ******************************/

/****************************** 函数方法 start ******************************/

/****************************** 函数方法 end ******************************/
const newFixedSearch = ref({})
let dsj = ref()
/****************************** 初始化 start ******************************/
const init = async () => {
  // 调用查看接口查询数据
  // await getMedicalOrderSee()
  newFixedSearch.value = {
    inventory_id: props.id
  }
  tableObject.fixedSearch = newFixedSearch.value
  getList()
}
init()

const Formatter = (row, column) => {
  const type = ref('1')
  if (column.property == 'breed') {
    type.value = row.breed
  } else if (column.property == 'breed_sub') {
    type.value = row.breed_sub
  } else if (column.property == 'purpose') {
    type.value = row.purpose
  }
  // console.log('kk', row, column)

  const ss = getDictLabel(column.property, type.value)
  // console.log(ss, 'kk', row, column)
  return ss
}

const animal_sex = (row) => {
  const ss = getDictLabel('animal_sex', row.sex)
  return ss
}

// const exportClick = async () => {
//   // dsj.value.tableList.push({ name: 'ks' })
//   dsj.value = []
//   // console.log(Math.ceil(tableObject.count / 10), dsj.value.tableList)
//   for (let index = 0; index < Math.ceil(tableObject.count / 10); index++) {
//     const { data } = await zcInventoryDetailedListApi({
//       inventory_id: props.id,
//       pageNo: index + 1,
//       pageSize: 10
//     })
//     for (let i = 0; i < data.length; i++) {
//       dsj.value.push(data[i])
//     }
//   }
//   console.log(dsj.value, 'data')

//   //第一个参数是到处后文件名，第二个是id绑定表格dom
//   nextTick(() => {
//     exportExcel('盘点报表', 'mainTable')
//   })
// }
// //转换数据
// const exportExcel = (filename, tableId) => {
//   var xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
//   var table = document.querySelector('#' + tableId).cloneNode(true)
//   var wb = XLSX.utils.table_to_book(table, xlsxParam)
//   /* 获取二进制字符进行输出 */
//   var wbout = XLSX.write(wb, {
//     bookType: 'xlsx',
//     bookSST: true,
//     type: 'array'
//   })
//   try {
//     FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), filename + '.xlsx')
//   } catch (e) {
//     if (typeof console !== 'undefined') {
//       console.log(e, wbout)
//     }
//   }
//   return wbout
// }

const tiao = async (value) => {
  // console.log(value)
  const { data } = await zcInventoryDetailedListApi({
    inventory_id: props.id,
    pageNo: value,
    pageSize: 10
  })

  dsj.value = data
}

const count = ref()
const ini = async () => {
  const res: any = await zcInventoryDetailedListApi({
    inventory_id: props.id,
    pageNo: 1,
    pageSize: 10
  })
  // console.log(res, 'data')
  count.value = res.count
  dsj.value = res.data
}
ini()

// 导出
const exportClick = async () => {
  dialogTableVisible.value = true

  const res = await dbInventorySeeexportApi({
    request: {
      id: props.id,
      pageNo: '1',
      pageSize: '10000'
    },
    layout_data: {
      file_name: '盘点单详情',
      column_cell_start: 'A4',
      column_value: 'detailed',
      column_data: [
        {
          title: '序号',
          width: 5,
          cell_type: 'key'
        },
        {
          title: '栏位名称',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'asset_enclosure_name'
        },
        {
          title: '资产编码（注射）',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'asset_code'
        },
        {
          title: '资产编码（项圈）',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'asset_code_2'
        },
        {
          title: '耳标',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'earcon_code'
        },
        {
          title: '畜别',
          width: 10,
          cell_type: 'dict',
          dict_type: 'breed',
          give_type: 'variable',
          give_value: 'breed'
        },
        {
          title: '品种',
          width: 10,
          cell_type: 'dict',
          dict_type: 'breed_sub',
          give_type: 'variable',
          give_value: 'breed_sub'
        },
        {
          title: '性别',
          width: 10,
          cell_type: 'dict',
          dict_type: 'animal_sex',
          give_type: 'variable',
          give_value: 'sex'
        },
        {
          title: '用途',
          width: 10,
          cell_type: 'dict',
          dict_type: 'purpose',
          give_type: 'variable',
          give_value: 'purpose'
        },
        {
          title: '应盘量',
          width: 10,
          cell_type: 'number',
          give_type: 'variable',
          give_value: 'should_number',
          sum: true
        },
        {
          title: '实盘量',
          width: 10,
          cell_type: 'number',
          give_type: 'variable',
          give_value: 'actual_number',
          sum: true
        },
        {
          title: '差异',
          width: 10,
          cell_type: 'formula',
          give_type: 'format',
          give_value: '=K${i}-J${i}',
          sum: true
        },
        {
          title: '备注',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'note'
        }
      ],
      custom: [
        {
          cell_type: 'string',
          cell: 'A1:M1',
          give_type: 'format',
          give_value: '${code}盘点单详情',
          horizontal: 'center',
          border: true,
          size: '16'
        },
        {
          cell_type: 'string',
          cell: 'A2:D2',
          give_type: 'format',
          give_value: '牧场名称：${pasture_name}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'E2:G2',
          give_type: 'format',
          give_value: '单号：${code}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell: 'H2:J2',
          cell_type: 'string',
          give_type: 'format',
          give_value: '盘点日期：${inventory_date}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'K2:M2',
          give_type: 'format',
          give_value: '状态：${dict.inventory_state.${state}}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'A3:D3',
          give_type: 'format',
          give_value: '牧场地址：${pasture_address}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'E3:G3',
          give_type: 'format',
          give_value: '规则名称：${inventory_rule_name}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'H3:M3',
          give_type: 'format',
          give_value: '盘点人：${create_user_name}',
          horizontal: 'left',
          border: true,
          size: '12'
        }
      ],
      dict: ['inventory_state']
    }
  })
  if (res) {
    // window.open(data.url)
    // console.log(res.data.count, Math.ceil(res.data.count / 10000))
    FormsNumber.value = Math.ceil(res.data.count / 10000)
  }
  console.log(res, 'res')
}

const FormsNumber = ref(0)
const dialogTableVisible = ref(false)

const Export = async (index) => {
  let { data }: any = await dbInventorySeeexportApi({
    request: {
      id: props.id,
      pageNo: index,
      pageSize: '10000'
    },
    layout_data: {
      file_name: '盘点单详情',
      column_cell_start: 'A4',
      column_value: 'detailed',
      column_data: [
        {
          title: '序号',
          width: 5,
          cell_type: 'key'
        },
        {
          title: '栏位名称',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'asset_enclosure_name'
        },
        {
          title: '资产编码（注射）',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'asset_code'
        },
        {
          title: '资产编码（项圈）',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'asset_code_2'
        },
        {
          title: '耳标',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'earcon_code'
        },
        {
          title: '畜别',
          width: 10,
          cell_type: 'dict',
          dict_type: 'breed',
          give_type: 'variable',
          give_value: 'breed'
        },
        {
          title: '品种',
          width: 10,
          cell_type: 'dict',
          dict_type: 'breed_sub',
          give_type: 'variable',
          give_value: 'breed_sub'
        },
        {
          title: '性别',
          width: 10,
          cell_type: 'dict',
          dict_type: 'animal_sex',
          give_type: 'variable',
          give_value: 'sex'
        },
        {
          title: '用途',
          width: 10,
          cell_type: 'dict',
          dict_type: 'purpose',
          give_type: 'variable',
          give_value: 'purpose'
        },
        {
          title: '应盘量',
          width: 10,
          cell_type: 'number',
          give_type: 'variable',
          give_value: 'should_number',
          sum: true
        },
        {
          title: '实盘量',
          width: 10,
          cell_type: 'number',
          give_type: 'variable',
          give_value: 'actual_number',
          sum: true
        },
        {
          title: '差异',
          width: 10,
          cell_type: 'formula',
          give_type: 'format',
          give_value: '=K${i}-J${i}',
          sum: true
        },
        {
          title: '备注',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'note'
        }
      ],
      custom: [
        {
          cell_type: 'string',
          cell: 'A1:M1',
          give_type: 'format',
          give_value: '${code}盘点单详情',
          horizontal: 'center',
          border: true,
          size: '16'
        },
        {
          cell_type: 'string',
          cell: 'A2:D2',
          give_type: 'format',
          give_value: '牧场名称：${pasture_name}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'E2:G2',
          give_type: 'format',
          give_value: '单号：${code}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell: 'H2:J2',
          cell_type: 'string',
          give_type: 'format',
          give_value: '盘点日期：${inventory_date}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'K2:M2',
          give_type: 'format',
          give_value: '状态：${dict.inventory_state.${state}}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'A3:D3',
          give_type: 'format',
          give_value: '牧场地址：${pasture_address}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'E3:G3',
          give_type: 'format',
          give_value: '规则名称：${inventory_rule_name}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'H3:M3',
          give_type: 'format',
          give_value: '盘点人：${create_user_name}',
          horizontal: 'left',
          border: true,
          size: '12'
        }
      ],
      dict: ['inventory_state']
    }
  })
    .catch(() => {})
    .finally(() => {
      // saveLoading.value = false
    })
  if (data) {
    window.open(data.url)

    console.log(data, Math.ceil(data.count / 10000))
    // FormsNumber.value = Math.ceil(data.count / 10000)
  }
}
</script>

<template>
  <div>
    <el-button
      style="margin-bottom: 20px"
      @click="exportClick"
      type="primary"
      size="small"
      :icon="Folder"
      >导出</el-button
    >

    <ContentWrap title="主数据">
      <Descriptions :schema="props.detailSchema" :data="props.currentRow">
        <template #inventory_rule_type="{ row }: { row: any }">
          <div>{{ getDictLabel('inventory_type', row.inventory_rule_type) }}</div>
        </template>
        <template #state="{ row }: { row: any }">
          <div>{{ getDictLabel('inventory_state', row.state) }}</div>
        </template>
      </Descriptions>
    </ContentWrap>

    <ContentWrap title="明细数据" v-show="false">
      <Table
        v-model:pageSize="tableObject.pageSize"
        v-model:currentPage="tableObject.currentPage"
        :columns="allSchemas.tableColumns"
        :data="tableObject.tableList"
        :loading="tableObject.loading"
        :border="true"
        :pagination="{
          total: tableObject.count
        }"
        @register="register"
        :selection="false"
      />
    </ContentWrap>

    <el-table :data="dsj" style="width: 100%" id="mainTable">
      <el-table-column label="盘点单" align="center">
        <el-table-column :label="`牧场名称：${props.currentRow.pasture_org_name}`" width="150">
          <el-table-column :label="`牧场地址：${props.currentRow.pasture_org_name}`" width="120">
            <el-table-column type="index" label="序号" width="70" />
            <el-table-column prop="enclosure_name" label="栏位" width="120" />
            <el-table-column prop="asset_code" label="注射编码" width="180" />
            <el-table-column prop="asset_code_2" label="项圈编码" width="180" />
          </el-table-column>
        </el-table-column>

        <el-table-column :label="`单号：${props.currentRow.code}`">
          <el-table-column :label="`规则名称：${props.currentRow.inventory_rule_name}`">
            <el-table-column prop="earcon_code" label="耳标" width="120" />
            <el-table-column prop="breed" label="畜别" width="120" :formatter="Formatter" />
            <el-table-column prop="breed_sub" label="品种" width="120" :formatter="Formatter" />
          </el-table-column>
        </el-table-column>

        <el-table-column :label="`盘点日期：${props.currentRow.inventory_date}`">
          <el-table-column :label="`盘点人：${props.currentRow.pasture_user_name}`">
            <el-table-column prop="sex" label="性别" width="120" :formatter="animal_sex" />
            <el-table-column prop="purpose" label="用途" width="120" :formatter="Formatter" />
            <el-table-column prop="should_number" label="应盘数" width="120" />
          </el-table-column>
        </el-table-column>

        <el-table-column :label="`状态：${props.currentRow.state == '1' ? '未盘点' : '已盘点'}`">
          <el-table-column>
            <el-table-column prop="actual_number" label="实盘数" width="120" />
            <el-table-column prop="actual_number" label="差异" width="120" />
            <el-table-column prop="note" label="备注" width="120" />
          </el-table-column>
        </el-table-column>
      </el-table-column>
    </el-table>
    <div class="example-pagination-block">
      <!-- <div class="example-demonstration">When you have more than 7 pages</div> -->
      <el-pagination layout="prev, pager, next" :total="count" @current-change="tiao" />
    </div>

    <el-dialog v-model="dialogTableVisible" title="盘点主档导出详情">
      <div style="margin: 20px" v-for="(item, index) in FormsNumber" :key="index">
        <span style="margin: 20px">盘点主档 - {{ item }}</span>
        <ElButton type="primary" @click="Export(item)">导出</ElButton>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.example-pagination-block + .example-pagination-block {
  margin-top: 10px;
}

.example-pagination-block .example-demonstration {
  margin-bottom: 16px;
}
</style>
